//
//  MineViewController.m
//  ChartsDemo
//
//  Created by wusiping on 2021/3/30.
//

#import "MineViewController.h"
#import "MineVCTableViewCell.h"
#import "LanguageViewController.h"
#import "PrivacyViewController.h"
#import "HelpViewController.h"
#import "DeviceManagerVC.h"
#import "ARTMainTabController.h"

@interface MineViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic,strong) UIImageView *icon;
@property (nonatomic,strong) UILabel *titleLabel;
@property (nonatomic,strong) UILabel *detailLabel;
@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,strong) NSArray *dataArray;

// 是否有新版本
@property (assign, nonatomic)  BOOL  isUpdate;

@end

@implementation MineViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self j_appearance];
    [self dataConfig];
    [self UIConfig];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refresh) name:ART_Notify_LanguageChanged object:nil];

    [self detectionVersion];
    
//#ifndef __OPTIMIZE__
/// Debug
//    UITapGestureRecognizer *hostTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(shareLogAction)];
//    hostTap.numberOfTapsRequired = 4;
//    [self.view addGestureRecognizer:hostTap];
//#else
///// release
//#endif
}

- (void)detectionVersion{
//    [QMUITips showLoadingInView:self.view];
    [ARTNetworkService request_checkAppVersion_WithParameter:@{} success:^(id  _Nullable json) {
//        [QMUITips hideAllTips];
        if ([json isKindOfClass:[NSDictionary class]]) {
            NSDictionary *data = (NSDictionary *)json;
            NSInteger updateFlag = [data j_integerForKey:@"updateFlag"];
            if (updateFlag == 1) {
                // 有新版本
                self.isUpdate = YES;
                [self.tableView reloadData];
            }
        }
    } failure:^(NSString * _Nonnull errorMSG) {
//        [QMUITips hideAllTips];
    }];
}


#pragma mark - dataConfig
- (void)dataConfig
{
    self.dataArray = @[
    @{@"imageName":@"me_ic_facility",@"title":FYLocalizedString(@"app__device_manage", @"")},
    @{@"imageName":@"me_ic_language",@"title":FYLocalizedString(@"app__language", @"")},
    @{@"imageName":@"me_ic_privacy",@"title":FYLocalizedString(@"app__declaration", @"")},
    @{@"imageName":@"me_ic_help",@"title":FYLocalizedString(@"app__help", @"")},
    @{@"imageName":@"shengji",@"title":FYLocalizedString(@"app__upgrade", @"")}
    ];
}

#pragma mark - UIConfig
- (void)UIConfig{
    [self.view setBackgroundColor:[UIColor colorWithString:@"#fbfbfb"]];
    self.icon = [[UIImageView alloc] init];
    self.icon.layer.cornerRadius = 20.f;
    self.icon.layer.masksToBounds = YES;
    self.icon.image = [UIImage imageNamed:@"me_ic_logo"];
    [self.view addSubview:self.icon];
    [_icon mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.mas_equalTo(90);
        make.centerX.equalTo(self.view);
        make.top.equalTo(self.view).offset(TOP_HEIGHT + 30);
    }];
    
    self.titleLabel = [[UILabel alloc] init];
    self.titleLabel.text = FYLocalizedString(@"app_acc_name", @"");
    self.titleLabel.font = [UIFont boldSystemFontOfSize:18];
    self.titleLabel.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:self.titleLabel];
    [_titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.centerX.equalTo(self.view);
        make.top.equalTo(self.icon.mas_bottom).offset(20);
    }];
    
    
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    self.detailLabel = [[UILabel alloc] init];
    self.detailLabel.text = [NSString stringWithFormat:@"V %@",app_Version];
    self.detailLabel.font = [UIFont boldSystemFontOfSize:12];
    self.detailLabel.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:self.detailLabel];
    [_detailLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.centerX.equalTo(self.view);
        make.top.equalTo(self.titleLabel.mas_bottom).offset(10);
    }];
    
    self.tableView = [[UITableView alloc] init];
    self.tableView.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0);
    self.tableView.separatorColor = [UIColor colorWithString:@"#F1F1F1"];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.tableView registerClass:[MineVCTableViewCell class] forCellReuseIdentifier:@"MineVCTableViewCell"];
    self.tableView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.detailLabel.mas_bottom).offset(30);
        make.left.equalTo(self.view.mas_left).offset(15);
        make.right.equalTo(self.view.mas_right).offset(-15);
        make.height.mas_equalTo(300);
    }];
    self.tableView.layer.cornerRadius = 10;
    self.tableView.layer.masksToBounds = YES;
    

    
}

#pragma mark - refresh
- (void)refresh
{
    self.titleLabel.text = FYLocalizedString(@"app_acc_name", @"");
    self.title = FYLocalizedString(@"app__my", @"");
    [self dataConfig];
    [self.tableView reloadData];
}



#pragma mark - UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    NSInteger count = 1;
    return count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSInteger count = self.dataArray.count;
    return count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MineVCTableViewCell *cell = (MineVCTableViewCell *)[self.tableView dequeueReusableCellWithIdentifier:@"MineVCTableViewCell"];
    if (!cell) {
        cell = [[MineVCTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                          reuseIdentifier:@"MineVCTableViewCell"];
    }
    NSDictionary *dict = self.dataArray[indexPath.row];
    BOOL need = (indexPath.row == (self.dataArray.count - 1)) ? NO:YES;
    [cell configWithImageName:[dict valueForKey:@"imageName"] text:[dict valueForKey:@"title"] needSeperateView:need];
    cell.rightImageView.hidden = NO;
    cell.rightLabel.hidden = YES;
    if (indexPath.row == 4 && _isUpdate) {
        cell.rightImageView.hidden = YES;
        cell.rightLabel.hidden = NO;
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    switch (indexPath.row) {
        case 0:{
            DeviceManagerVC *vc = [[DeviceManagerVC alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
        case 1:
        {
            ARTMainTabController *tabbarVC = (ARTMainTabController *)self.tabBarController;
//            if (tabbarVC.monitorDevType == ARTDeviceTypeWatch) {
//                [QMUITips showWithText:@"睡眠功能暂不支持切换语言"];
//                return;
//            }
            LanguageViewController *vc = [[LanguageViewController alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
        case 2:{
            PrivacyViewController *vc = [[PrivacyViewController alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
            
        case 3:{
            HelpViewController *vc = [[HelpViewController alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
            
        case 4:{
            if (_isUpdate) {
                NSURL *url = [NSURL URLWithString:kDownloadAPPURL];
                if ([[UIApplication sharedApplication] canOpenURL:url]) {
                    [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:nil];
                }
            }else{
                [QMUITips showWithText:FYLocalizedString(@"new_version", @"")];
            }
        }
            break;
            
        default:
            break;
    }    
}

#pragma mark--测试
- (void)shareLogAction{
    NSString *documentDirectory = J_Path_Document;
    NSString *fileName = [NSString stringWithFormat:@"test.txt"];
    NSString *logFilePath = [documentDirectory stringByAppendingPathComponent:fileName];
    NSData *shareData = [NSData dataWithContentsOfFile:logFilePath];
    if (shareData.length == 0) {
        [QMUITips showWithText:@"暂无日志分享"];
        return;
    }
    NSArray *activityItems = @[shareData,[NSURL URLWithString:logFilePath]];
    UIActivityViewController *activityVC = [[UIActivityViewController alloc]initWithActivityItems:activityItems applicationActivities:nil];
    [self presentViewController:activityVC animated:YES completion:nil];
    // 分享之后的回调
    J_WeakSelf(activityVC)
    activityVC.completionWithItemsHandler = ^(UIActivityType  _Nullable activityType, BOOL completed, NSArray * _Nullable returnedItems, NSError * _Nullable activityError) {
        J_StrongSelf(activityVC)
        if (completed) {
            // 分享成功
            [activityVC dismissViewControllerAnimated:YES completion:nil];
            if (activityError) {
                [QMUITips showWithText:FYLocalizedString(@"share_fail", @"")];
            }else{
                [QMUITips showWithText:FYLocalizedString(@"share_success", @"")];
            }
        } else  {
            NSLog(@"cancled");
            //分享 取消
            [activityVC dismissViewControllerAnimated:YES completion:nil];
            [QMUITips showWithText:FYLocalizedString(@"share_cancel", @"")];
        }
    };
}


@end
